package com.hzcx.app.simplechat.ui.publicui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.model.GroupModel;
import com.hzcx.app.simplechat.ui.chat.bean.GroupSearchBean;
import com.hzcx.app.simplechat.ui.group.AddGroupForSearchActivity;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.home.AddFriendActivity;
import com.hzcx.app.simplechat.ui.mine.EditUserInfoActivity;
import com.hzcx.app.simplechat.ui.mine.MineUserInfoActivity;
import com.hzcx.app.simplechat.ui.publicui.contract.CaptureContract;
import com.hzcx.app.simplechat.ui.publicui.presenter.CapturePresenter;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.util.TextHttpUtil;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.file.FileUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.photo.PhotoUtil;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.ToastUtils;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;

/**
 * 扫描二维码界面
 */
public class CaptureActivity extends BaseActivity<CapturePresenter> implements QRCodeView.Delegate, CaptureContract.View, OnResultCallbackListener<LocalMedia> {
    @BindView(R.id.zbar_view)
    ZBarView zbarView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_photo)
    TextView tvPhoto;

    @Override
    public int getLayout() {
        return R.layout.activity_capture;
    }

    @Override
    public void initPresenter() {
        mPresenter = new CapturePresenter();
    }

    @Override
    public void initView() {
        changeStatusBarTextColor(false);

        zbarView.setDelegate(this);
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.tv_photo})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_photo:
                PhotoUtil.showPhoto(this, PictureMimeType.ofImage(), PictureConfig.SINGLE, false, false, null, this);
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        zbarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别

        zbarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        zbarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        zbarView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i(TAG, "result:" + result);
        vibrate();
        if (EmptyUtils.isEmpty(result)) {
            showError("未识别到二维码内容");
            finish();
            return;
        }
        zbarView.stopCamera();
        if (result.contains("chat_number")) {
            // 如果是多聊二维码，调用接口
            mPresenter.getUserInfoByQrCode(this, result);
        } else if (result.contains("group_number")) {
            // 如果是多聊二维码，调用接口
            // FIXME:  跳转多聊群
            // http://down.dlchat.cc/index.php/api/group/qrcode_group_info?group_number=189006
            String[] list = result.split("=");
            if (list.length == 2) {
                String groupid = list[1];
                GroupModel.searchGroupList(this, groupid,"", new BaseObserver<List<GroupSearchBean>>() {
                    @Override
                    protected void onSuccess(List<GroupSearchBean> data) {
                        if (data.size() <= 0) {
                            showError("未查到群组信息");
                        } else {
                            GroupSearchBean groupInfoBean = data.get(0);
                            if (groupInfoBean != null) {
                                Intent intent = new Intent(CaptureActivity.this, AddGroupForSearchActivity.class);
                                intent.putExtra(AddGroupForSearchActivity.bean, groupInfoBean);
                                startActivity(intent);
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
            }

        } else if (TextHttpUtil.hasNetUrlHead(result)) {
            // 网页链接，跳转到web界面
            startActivity(new Intent(this, WebViewActivity.class)
                    .putExtra(WebViewActivity.INTENT_WEB_URL, result));
            finish();
        } else {
            // 都不是，直接展示结果
            startActivity(new Intent(this, CaptureResultActivity.class)
                    .putExtra(CaptureResultActivity.INTENT_RESULT, result));
            finish();
        }
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        String tipText = zbarView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                zbarView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                zbarView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        showError("打开相机出错,请稍后重试");
    }

    /**
     * 用户信息获取成功
     *
     * @param data
     */
    @Override
    public void userInfoResult(UserInfoBean data) {
        if (data.getMember_id() == UserInfoUtil.getUserId()) {
            startActivity(new Intent(this, MineUserInfoActivity.class));
            finish();
            return;
        }
        if (data.getIs_buddy() == 1) {
            startActivity(new Intent(this, UserInfoActivity.class)
                    .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
        } else {
            startActivity(new Intent(this, AddFriendActivity.class)
                    .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id())
                    .putExtra(AddFriendActivity.INTENT_TYPE, 2));
        }
//        zbarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
        finish();
    }

    /**
     * 用户信息获取失败
     */
    @Override
    public void onFail() {
        zbarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    /**
     * 选取照片返回
     *
     * @param result
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        zbarView.stopCamera();
        String path = PhotoUtil.getPath(result.get(0));
        File file = new File(path);
        if (!file.exists()) {
            path = FileUtils.getImageAbsolutePath(this, Uri.parse(path));
        }
        LogUtils.d("path:" + path);
        zbarView.decodeQRCode(path);
    }

    @Override
    public void onCancel() {

    }
}
